<template>
  <div class="PageForm">
    <client-only>
      <el-config-provider :size="'default'">
        <el-form
          ref="ruleFormRef"
          :model="formDatas"
          :rules="rules"
          :label-position="
            labelPosition === 'top' ||
            labelPosition === 'left' ||
            labelPosition === 'right'
              ? labelPosition
              : 'right'
          "
        >
          <!-- :label-width="width ? width : '130px'" -->

          <el-row
            v-for="(item, index) in list"
            :key="index"
            :gutter="gutter || 20"
          >
            <template v-for="(target, key) in item.list" :key="key">
              <el-col
                v-if="!target.hidden"
                :span="target.span"
                style="padding: 0px"
              >
                <el-form-item
                  style=" margin-bottom: 17px"
                  :label-width="
                    target.labelWidth || width
                      ? target.labelWidth || width
                      : '130px'
                  "
                  :label="target.label ? target.label : ''"
                  :prop="target.prop"
                >
                  <template v-if="target.component === 'input'">
                    <div style="display: flex; align-items: center">
                      <el-input
                        v-model="formDatas[target.prop]"
                        :style="{
                          width: target.componentProps?.width
                            ? target.componentProps?.width
                            : '300px',
                        }"
                        :disabled="target.disabled"
                        :placeholder="target.componentProps?.placeholder"
                      >
                        <template
                          v-if="target.componentProps?.prepend"
                          #prepend
                        >
                          <div style="text-align: right; width: 70px">
                            {{ target.componentProps?.prepend }}
                          </div>
                          <!-- <slot :name="target.componentProps?.prepend" /> -->
                        </template>

                        <template v-if="target.componentProps?.append" #append>
                          <slot :name="target.componentProps?.append" />
                        </template>
                      </el-input>
                      <span
                        v-if="target.componentProps?.rightText"
                        :style="
                          target.componentProps?.textLmargin
                            ? 'margin-left: ' +
                              target.componentProps?.textLmargin +
                              ';'
                            : 'margin-left: 22px'
                        "
                        >{{ target.componentProps?.rightText }}</span
                      >
                    </div>
                  </template>
                  <template v-if="target.component === 'password'">
                    <div style="display: flex; align-items: center">
                      <div>********</div>
                      <el-button
                        style="margin-left: 12px"
                        type="primary"
                        @click="target.componentProps?.onClick"
                        >{{
                          target.componentProps?.buttonText
                            ? target.componentProps?.buttonText
                            : '修改'
                        }}</el-button
                      >
                    </div>
                  </template>
                  <template
                    v-if="target.component === 'input2'"
                    class="flex-container"
                  >
                    <div>
                      <el-input
                        v-model="formDatas[target.prop]"
                        :style="{
                          width: target.componentProps?.width
                            ? target.componentProps?.width
                            : '300px',
                        }"
                        :disabled="target.disabled"
                        :placeholder="target.componentProps?.placeholder"
                      >
                        <template
                          v-if="target.componentProps?.prepend"
                          #prepend
                        >
                          <div style="text-align: right; width: 70px">
                            {{ target.componentProps?.prepend }}
                          </div>
                          <!-- <slot :name="target.componentProps?.prepend" /> -->
                        </template>

                        <template v-if="target.componentProps?.append" #append>
                          <slot :name="target.componentProps?.append" />
                        </template>
                      </el-input>
                      <span style="padding: 0 10px"> - </span>
                      <el-input
                        v-model="formDatas[target.prop + '2']"
                        :style="{
                          width: target.componentProps?.width2
                            ? target.componentProps?.width2
                            : '300px',
                        }"
                        :disabled="target.disabled"
                        :placeholder="target.componentProps?.placeholder"
                      >
                      </el-input>
                    </div>
                    <div class="prompt-container">
                      {{ target.componentProps?.prompt }}
                    </div>

                    <!-- <el-tooltip
                      class="box-item"
                      effect="dark"
                      :content="target.componentProps?.prompt"
                      placement="right-end"
                      style="margin-left: 10px"
                    >
                      <span>
                        <Icon
                          style="font-size: 20px; margin-top: 2px"
                          :name="'material-symbols:help'"
                        />
                      </span>
                    </el-tooltip> -->
                  </template>
                  <template v-else-if="target.component === 'textarea'">
                    <el-input
                      v-model="formDatas[target.prop]"
                      :style="`width: ${
                        target.componentProps?.width || '300px'
                      }`"
                      :autosize="{ minRows: 5, maxRows: 6 }"
                      type="textarea"
                      class="textarea1"
                      v-bind="target.componentProps"
                    />
                  </template>
                  <template v-else-if="target.component === 'number'">
                    <el-input-number
                      v-model="formDatas[target.prop]"
                      v-bind="target.componentProps"
                      :min="target.min ? target.min : 0"
                      :style="{
                        width: target.componentProps?.width
                          ? target.componentProps?.width
                          : '300px',
                      }"
                      :disabled="target.disabled"
                      :max="target.max"
                      controls-position="right"
                      size="large"
                      @input="target.onInput"
                    />
                  </template>
                  <template v-else-if="target.component === 'button'">
                    <el-button v-bind="target.componentProps" />
                  </template>

                  <template v-else-if="target.component === 'switch'">
                    <el-switch
                      v-model="formDatas[target.prop]"
                      v-bind="target.componentProps"
                      :active-value="target.active"
                      :inactive-value="target.inactive"
                      @click="
                        () =>
                          target?.switchProps?.onChange(formDatas[target.prop])
                      "
                    />
                  </template>
                  <template v-else-if="target.component === 'treeSelect'">
                    <el-tree-select
                      v-model="formDatas[target.prop]"
                      :data="target.treeSelectList"
                      check-strictly
                      :render-after-expand="false"
                      :multiple="target.multiple"
                      :show-checkbox="target.checkbox"
                    />
                  </template>

                  <template v-else-if="target.component === 'radioGroup'">
                    <el-radio-group
                      v-model="formDatas[target.prop]"
                      v-bind="target.componentProps"
                      :disabled="target.disabled"
                    >
                      <el-radio
                        v-for="option in target.radioGroupOptions"
                        :key="option.label"
                        :value="option.value"
                      >
                        {{ option.label }}
                      </el-radio>
                    </el-radio-group>
                  </template>

                  <template v-else-if="target.component === 'select'">
                    <!-- <el-select-v2
                    
                      filterable
                      
                     
                      :options="
                        target.selectGroupOptions
                          ? target.selectGroupOptions
                          : []
                      "
                      :multiple="target.multiple"
                      
                      @change="target.onSelect"
                      :value-key="'value'"
                    >
                      <template #header v-if="target.multiple">
                        <el-checkbox
                          v-model="checkAll"
                          :indeterminate="indeterminate"
                          @change="handleCheckAll(target)"
                        >
                          全选
                        </el-checkbox>
                      </template>
                      <template
                        #label="{ label, value }"
                        v-if="target.componentProps?.customize"
                      >
                        <span>{{ value }}</span>
                      </template>
                    </el-select-v2> -->

                    <el-select
                      v-model="formDatas[target.prop]"
                      filterable
                      clearable
                      :multiple="target.multiple"
                      @change="target.onSelect"
                      :placeholder="
                        target.componentProps?.placeholder
                          ? target.componentProps?.placeholder
                          : '请选择'
                      "
                      :style="`width: ${
                        target.componentProps?.width || '300'
                      }px`"
                    >
                      <el-option
                        v-for="(item, index) in target?.selectGroupOptions"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>

                    <span
                      v-if="target.labelR"
                      :style="`margin-left:${target.labelRNum || 10}px`"
                    >
                      {{ target.labelR }}
                    </span>
                  </template>
                  <template v-else-if="target.component === 'date'">
                    <el-date-picker
                      v-model="formDatas[target.prop]"
                      type="date"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      :placeholder="
                        target.componentProps?.placeholder
                          ? target.componentProps?.placeholder
                          : '请选择'
                      "
                      :style="`width: ${
                        target.componentProps?.width || '300'
                      }px;margin-left: ${target.labelLNum}px`"
                    />
                  </template>
                  <template v-else-if="target.component === 'time'">
                    <el-time-picker
                      v-model="formDatas[target.prop]"
                      format="HH:mm"
                      :style="`width: ${
                        target.componentProps?.width || '300px'
                      };`"
                      value-format="HH:mm"
                      arrow-control
                      placeholder="选择时间"
                    />
                  </template>
                  <template v-else-if="target.component === 'daterange'">
                    <el-date-picker
                      v-model="formDatas[target.prop]"
                      type="daterange"
                      size="large"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                    />
                  </template>
                  <template v-else-if="target.component === 'cascader'">
                    <el-cascader
                      v-model="formDatas[target.prop]"
                      :options="getCascaderOptions(target)"
                      :props="
                        target.cascaderProps || {
                          value: 'code',
                          label: 'name',
                          children: 'children',
                        }
                      "
                      :style="{
                        width: target.componentProps?.width
                          ? target.componentProps?.width
                          : '300px',
                      }"
                      :placeholder="
                        target.componentProps?.placeholder || '请选择省市县'
                      "
                      @change="(value) => handleRegionChange(value, target)"
                      clearable
                      filterable
                    />
                  </template>
                  <template v-else-if="target.component === 'upload'">
                    <el-upload
                      :limit="1"
                      ref="upload"
                      :before-upload="target.beforeUpload"
                    >
                      <el-button
                        style="margin-left: 10px"
                        size="small"
                        type="primary"
                      >
                        上传图片
                      </el-button>
                    </el-upload>
                  </template>
                  <template v-else-if="target.component === 'imgUpload'">
                    <div>
                      <el-upload
                        ref="upload"
                        :before-upload="target.beforeUpload"
                        :on-change="target.onSuccess"
                        :show-file-list="false"
                      >
                        <img
                          v-if="formDatas[target.prop]"
                          :src="formDatas[target.prop]"
                          class="avatar"
                        />
                        <div v-else style="margin-top: 17px">
                          <el-icon><Plus /></el-icon>
                          <div class="el-upload__text">点击上传图片</div>
                        </div>
                      </el-upload>
                      <div style="color: rgba(0, 0, 0, 0.4)">
                        请上传不超过1MB的JPG、JPEG、PNG图片
                      </div>
                    </div>
                  </template>
                  <template v-else-if="target.component === 'avatarUpload'">
                    <el-upload
                      :file-list="formDatas[target.prop]"
                      ref="upload"
                      :before-upload="target.beforeUpload"
                      :on-change="target.onSuccess"
                      class="avatar-uploader"
                      :show-file-list="false"
                    >
                      <div class="avatar-upload-container">
                        <img
                          v-if="
                            formDatas[target.prop] &&
                            formDatas[target.prop].length > 0
                          "
                          :src="formDatas[target.prop][0].url"
                          class="avatar-image"
                          alt="头像"
                        />
                        <div v-else class="avatar-placeholder">
                          <el-icon class="avatar-uploader-icon">
                            <img
                              src="/assets/manage/empList/icon_shangcuan_nor.svg"
                              alt=""
                            />
                          </el-icon>
                        </div>
                      </div>
                    </el-upload>
                  </template>
                  <template v-else-if="target.component === 'text'">
                    <el-upload
                      :limit="1"
                      ref="textupload"
                      :before-upload="target.beforeUpload"
                      :on-exceed="target.handleExceed"
                    >
                      <el-button size="default" type=""> 上传文件 </el-button>
                    </el-upload>
                  </template>

                  <template v-else-if="target.component === 'content'">
                    {{ formDatas[target.prop] }}
                  </template>
                  <template v-else-if="target.component === 'slotName'">
                    <slot :name="target.componentProps?.slotName" />
                  </template>
                  <template v-else-if="target.component === 'slot'">
                    <slot />
                  </template>
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </el-form>
        <slot name="channel" />
      </el-config-provider>
    </client-only>
  </div>
</template>

<script setup lang="ts">
import type {
  FormRules,
  FormInstance,
  ElUpload,
  CascaderValue,
} from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { ref, watchEffect, onMounted } from 'vue';
import type { PageFormList } from '@/types/PageForm';
import stores from '@/store';
const useBaseData = stores.useBaseDataStore();
const props = defineProps<{
  list: PageFormList;
  formData: Record<string, any>;
  rules?: FormRules;
  width?: string;
  labelPosition?: string;
  gutter?: any;
}>();
const formDatas = ref<any>({});
const textupload = ref<InstanceType<typeof ElUpload> | any>(null);
const clearFiles = () => {
  if (textupload?.value) {
    textupload.value[0].clearFiles(); // 清除文件列表
  }
};
watchEffect(() => {
  formDatas.value = props.formData;
});

const loadingRegion = ref(false);

// 处理级联选择器的数据
const getCascaderOptions = (field: any) => {
  return useBaseData.regions;
};

// 处理区域变化
const handleRegionChange = (
  value: CascaderValue | null | undefined,
  field: any
) => {
  if (field.onChange) {
    field.onChange(value);
  }

  // 如果是区域选择，可以设置完整地址
  // if (value && Array.isArray(value) && value.length > 0) {
  //   const codes = value as number[];
  //   const fullAddress = regionUtils.getFullAddress(codes, regionData.value);
  //   // 可以设置到其他字段中，比如 address 字段
  //   if (field.addressProp) {
  //     formDatas.value[field.addressProp] = fullAddress;
  //   }
  // }
};

const checkAll = ref(false);
const indeterminate = ref(false);

const handleCheckAll = (target: any) => {
  if (checkAll.value) {
    formDatas.value[target.prop] = target.selectGroupOptions.map(
      (option: any) => option.value
    );
  } else {
    formDatas.value[target.prop] = [];
  }
  indeterminate.value = false;
};
const ruleFormRef: object = ref<FormInstance>();
onMounted(() => {
  // 确保Monaco Editor已经挂载并可用
  // 加载区域数据
});
defineExpose({
  ruleFormRef,
  clearFiles,
  textupload,
});
</script>

<style scoped lang="scss">
.PageForm {
  width: 100%;
  height: 100%;
}
</style>
<style lang="scss">
.PageForm {
  .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-upload {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    text-align: center;
    display: block;
    line-height: 25px;
  }
  .monaco-editor {
    background-color: red !important;
    /* 强制覆盖背景颜色 */
  }

  /* 设置滚动条的宽度 */
  .monaco-editor .scrollbar {
    width: 12px;
    /* 设置滚动条宽度 */
  }

  /* 自定义滚动条的轨道 */
  .monaco-editor .scrollbar .scrollbar-track {
    background: #f0f0f0;
    /* 设置滚动条背景 */
  }

  /* 自定义滚动条滑块 */
  .monaco-editor .scrollbar .scrollbar-thumb {
    background: #888;
    /* 设置滑块颜色 */
  }

  /* 为滚动条增加 hover 效果 */
  .monaco-editor .scrollbar .scrollbar-thumb:hover {
    background: #555;
    /* 鼠标悬停时的颜色 */
  }
  .flex-container {
    display: flex;
    flex-wrap: wrap; /* 允许子元素换行 */
    gap: 10px; /* 子元素之间的间距 */
  }
  .prompt-container {
    white-space: pre-wrap; /* 保留空白符并自动换行 */
    word-wrap: break-word; /* 强制长单词换行 */
    word-break: break-all; /* 强制长单词换行 */
    width: 100%; /* 使提示信息占据整行 */
    height: 20px;
    color: #666;
  }
  .el-upload__text {
    font-size: 12px;
    width: 100%;
    line-height: 20px;
  }

  /* 头像上传样式 */
  .avatar-uploader {
    .el-upload {
      border-radius: 50%;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      width: 80px;
      height: 80px;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0;
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
  }

  .avatar-upload-container {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    overflow: hidden;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    background-image: url('@/assets/manage/empList/img_yuangong_nor.svg');
    background-size: 100% 100%;
  }
  .avatar {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 50%;
  }

  .avatar-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    color: #8c939d;
  }

  .avatar-uploader-icon {
    font-size: 24px;
    margin-bottom: 4px;
  }

  .upload-text {
    font-size: 12px;
    text-align: center;
    line-height: 1.2;
  }
}
</style>
